/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "fr_local.h"

/*-----------------------------------------------------------------------------
	Shading system :
-----------------------------------------------------------------------------*/

//
//	EFRShadingSystem::EFRShadingSystem
//
EFRShadingSystem::EFRShadingSystem( EFRScene *scene )
{
	this->scene		=	scene;
	current_tech	=	FR_TECH_SOLID;
	

	LOG_INIT("Shading system");
}


//
//	EFRShadingSystem::~EFRShadingSystem
//
EFRShadingSystem::~EFRShadingSystem( void )
{
	LOG_SHUTDOWN("Shading system");
	ClearEffects();
}


//
//	EFRShadingSystem::ReloadShader
//
void EFRShadingSystem::ReloadShader( void )
{
	CoreExecuteString("package.loaded['shaders'] = nil");
	CoreExecuteString("require('shaders')");
	CoreExecuteString("shaders.defineShaders()");
}


//
//	EFRShadingSystem::ClearEffects
//
void EFRShadingSystem::ClearEffects( void )
{
	effects.clear();
}

//
//	EFRShadingSystem::DefineShader
//
void EFRShadingSystem::DefineShader( lua_State *L )
{
	try {
		EString name = "";
		LuaGetField( L, 1, "name", name );

		//	check field name :		
		if (name=="") {
			RUNTIME_ERROR("field 'name' is not specified");
		}
		
		LOGF("...shader : %s", name.CStr());

		//	try to update existing shader :
		for (uint i=0; i<shaders.size(); i++) {
			if (shaders[i]->Name()==name) {
				shaders[i]->UpdateShader( L, 1 );
				return;
			}
		}

		//	create new shader :
		HardRef<EFRShader>	shader	=	new EFRShader( scene, name, L, 1 );
		shaders.push_back( shader );
		
	} catch (exception &e) {
		LOG_WARNING("%s", e.what());
	}
}


//
//	EFRShadingSystem::GetShader
//
HardRef<EFRShader> EFRShadingSystem::GetShader( const EString name, bool recursive_call /* = false */ )
{
	for (uint i=0; i<shaders.size(); i++) {
		if (shaders[i]->Name()==name) {
			return shaders[i];
		}
	}
	
	try {
		if (!recursive_call) {
			LOG_WARNING("shader '%s' not found, calling shader fallback.", name.CStr());
			CoreExecuteString(va("shaders.defineShaderFB('%s')", name.CStr()), true);
		} else {
			RUNTIME_ERROR("recursive call to "__FUNCTION__);
		}
		
	} catch (exception &e) {
		LOG_WARNING("fallback failed:");
		LOG_WARNING("%s", e.what());
		LOG_WARNING("creating default", e.what());
		CoreExecuteString(va("render.defineShader { name = '%s'; injection=''; }", name.CStr()));
	}
	
	return GetShader(name, true);
}


//
//	EFRShadingSystem::GetEffect
//
IPxEffect EFRShadingSystem::GetEffect( const EString path, const EString injection )
{
	//	search for already loaded effect :
	for (uint i=0; i<effects.size(); i++) {
		if (effects[i].path == path && effects[i].injection == injection) {
			return effects[i].effect;
		}
	}

	//	effect was not found, create new :
	effect_s eff;
	
	EFXMacro	macro_injection;
	macro_injection.name		=	"SURFACE_SHADER";
	macro_injection.definition	=	injection;
	
	eff.path		=	path;
	eff.injection	=	injection;
	eff.effect		=	scene->rs->Driver()->GetFXM()->CompileEffect( path.CStr(), 1, &macro_injection );
	
	effects.push_back( eff );

	return eff.effect;
}

